package com.itheima.service.impl;

import com.itheima.domain.LoginResult;
import com.itheima.domain.PageResult;
import com.itheima.domain.User;
import com.itheima.domain.query.UserQueryParam;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;

    @Override
    public LoginResult login(User user) {
        //1、查询用户
        User userInfo = userMapper.login(user);

        //2、如果能查询到，则生成令牌
        if(userInfo!=null){
            //将第1个参数的属性值，复制给第2个参数
            LoginResult loginResult = new LoginResult();
            BeanUtils.copyProperties(userInfo,loginResult);
            //生成token令牌
            Map<String,Object> payload = new HashMap<>();
            payload.put("id",userInfo.getId());
            payload.put("username",userInfo.getUsername());
            payload.put("name",userInfo.getName());
            String token = JwtUtils.generateJwt(payload);
            loginResult.setToken(token);
            return loginResult;
        }
        //3、否则返回null
        return null;
    }
    @Override
    public PageResult list(UserQueryParam userQueryParam) {
        Integer total = userMapper.getTotal(userQueryParam);
        List<User> userList = userMapper.list(userQueryParam);
        return PageResult.<User>builder().total(total).data(userList).code(1).build();
    }
}
